﻿/*
Copyright (c) 2010, hiSoft
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the hiSoft nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE HISOFT AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL HISOFT BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;

namespace Orchard.Test.Library
{
    public class RoleHelper:UIHelperBase
    {
        public RoleHelper(TestLibrary settings) : base(settings) { }

        public void ManageRoles()
        {
            selenium.Open("/Admin/Roles");

        }

        public bool IsRolePresent(Role role)
        {
            ManageRoles();
            return selenium.IsTextPresent(role.Name);
        }

        public Role AddRole(string roleName)
        {
            selenium.Open("/Admin/Roles/Create");
            selenium.Type("Name", roleName);
            Submit();
            return new Role(TestSettings, roleName);
        }

        private Role AddRole(string roleName, List<string> permissions, bool check)
        {
            selenium.Open("/Admin/Roles/Create");
            selenium.Type("Name", roleName);
            int modulesCount = (int)selenium.GetXpathCount(ModulesPermissionLocator);
            for (int moduleIndex = 1; moduleIndex <= modulesCount; moduleIndex++)
            {
                string permissionsLocator = String.Format("{0}[{1}]/table/tbody/tr", ModulesPermissionLocator, moduleIndex);
                int permissionsCount = (int)selenium.GetXpathCount(permissionsLocator);
                for (int permissionIndex = 1; permissionIndex <= permissionsCount; permissionIndex++)
                {
                    string permissionCheckbox = String.Format("{0}[{1}]/td[2]/input", permissionsLocator, permissionIndex);
                    string permissionName = selenium.GetAttribute(String.Format("{0}/@name", permissionCheckbox)).Substring(9);
                    if (check)
                    {
                        if (permissions != null && permissions.Contains(permissionName))
                        {
                            selenium.Check(permissionCheckbox);
                        }
                    }
                    else
                    {
                        if (permissions != null && permissions.Contains(permissionName))
                        {
                            selenium.Uncheck(permissionCheckbox);
                        }
                        else
                        {
                            selenium.Check(permissionCheckbox);
                        }
                    }
                }
            }
            Submit();
            return new Role(TestSettings, roleName);
        }

        public Role AddRoleWithoutPermissions(string roleName, List<string> permissions)
        {
            return AddRole(roleName, permissions, false);
        }

        public Role AddRoleWithPermissions(string roleName, List<string> permissions)
        {
            return AddRole(roleName, permissions, true);
        }

        public Role EditRole(Role role, string newName, bool clickRemove)
        {
            ManageRoles();
            int roleIndex = role.GetRoleIndexOnManageRolesPage();
            ClickAndWait(String.Format("{0}[{1}]/td[3]/a", RolesLocator, roleIndex));            
            selenium.Type("Name", newName);
            if (clickRemove)
            {
                ClickAndWait("//button[@name='submit.Delete']");              
            }
            else
            {
                ClickAndWait("//button[@name='submit.Save']");              
            }
            
            return new Role(TestSettings, newName);
        }

        public Role EditRole(Role role, string newName, List<string> permissionsToRemove, List<string> permissionsToAdd)
        {
            ManageRoles();
            int roleIndex = role.GetRoleIndexOnManageRolesPage();
            ClickAndWait(String.Format("{0}[{1}]/td[3]/a", RolesLocator, roleIndex));
            selenium.Type("Name", newName);

            int modulesCount = (int)selenium.GetXpathCount(ModulesPermissionLocator);
            for (int moduleIndex = 1; moduleIndex <= modulesCount; moduleIndex++)
            {
                string permissionsLocator = String.Format("{0}[{1}]/table/tbody/tr", ModulesPermissionLocator, moduleIndex);
                int permissionsCount = (int)selenium.GetXpathCount(permissionsLocator);
                for (int permissionIndex = 1; permissionIndex <= permissionsCount; permissionIndex++)
                {
                    string permissionCheckbox = String.Format("{0}[{1}]/td[2]/input", permissionsLocator, permissionIndex);
                    string permissionName = selenium.GetAttribute(String.Format("{0}/@name", permissionCheckbox)).Substring(9);

                    if (permissionsToRemove != null && permissionsToRemove.Contains(permissionName))
                    {
                        selenium.Uncheck(permissionCheckbox);
                    }
                    if (permissionsToAdd != null && permissionsToAdd.Contains(permissionName))
                    {
                        selenium.Check(permissionCheckbox);
                    }
                }
            }
            ClickAndWait("//button[@name='submit.Save']"); 

            return new Role(TestSettings, newName);
        }

        public void RemovePermissionsFromRole(Role role, List<string> permissions)
        {
            ManageRoles();
            int roleIndex = role.GetRoleIndexOnManageRolesPage();
            ClickAndWait(String.Format("{0}[{1}]/td[3]/a", RolesLocator, roleIndex));            
            int modulesCount = (int)selenium.GetXpathCount(ModulesPermissionLocator);
            for (int moduleIndex = 1; moduleIndex <= modulesCount; moduleIndex++)
            {
                string permissionsLocator = String.Format("{0}[{1}]/table/tbody/tr", ModulesPermissionLocator, moduleIndex);
                int permissionsCount = (int)selenium.GetXpathCount(permissionsLocator);
                for (int permissionIndex = 1; permissionIndex <= permissionsCount; permissionIndex++)
                {
                    string permissionCheckbox = String.Format("{0}[{1}]/td[2]/input", permissionsLocator, permissionIndex);
                    string permissionName = selenium.GetAttribute(String.Format("{0}/@name", permissionCheckbox)).Substring(9);

                    if (permissions != null && permissions.Contains(permissionName))
                    {
                        selenium.Uncheck(permissionCheckbox);
                    }
                }               
            }           
            ClickAndWait("//button[@name='submit.Save']");           
        }

        public void DeleteRole(Role role)
        {
            ManageRoles();
            int index = role.GetRoleIndexOnManageRolesPage();
            ClickAndWait(String.Format("{0}[{1}]/td[3]/a[2]", RolesLocator, index));                       
        }

        public void SelectDeleteRoles(List<Role> roles)
        {
            ManageRoles();
            if (roles != null && roles.Count != 0)
            {
                foreach (Role role in roles)
                {
                    int roleIndex = role.GetRoleIndexOnManageRolesPage();
                    selenium.Check(String.Format("{0}[{1}]/td[1]/input", RolesLocator, roleIndex));
                }
            }        
            Submit(); 
        }

        public void DoSelectDeleteOnRoles(List<Role> roles)
        {           
            if (roles != null && roles.Count != 0)
            {
                foreach (Role role in roles)
                {
                    int roleIndex = role.GetRoleIndexOnManageRolesPage();
                    selenium.Check(String.Format("{0}[{1}]/td[1]/input", RolesLocator, roleIndex));
                }
            }
            Submit();
        }

        public int GetRoleCountOnManageRoles()
        {
            ManageRoles();
            return (int)selenium.GetXpathCount(RolesLocator);
        }    
    }

    public class Role:UIHelperBase
    {
        public string Name { get; set; }

        public Role(TestLibrary settings, string name):base(settings)
        {
            Name = name;
        }     

        public int GetRoleIndexOnManageRolesPage()
        {          
            var count = (int)selenium.GetXpathCount(RolesLocator);
            var index = 1;
            for (; index <= count; ++index)
            {
                string path = String.Format("{0}[{1}]/td[2]/a", RolesLocator, index);
                var text = selenium.GetText(path);
                if (String.CompareOrdinal(Name, text) == 0)
                    break;
            }

            if (index > count)
                throw new CaseFailureException(String.Format("Can't find role {0} in Manage Roles page!", Name));

            return index;
        }

        public int GetRoleIndexOnAddUserPage()
        {
            var count = (int)selenium.GetXpathCount(RolesLocatorForAddUser);
            var index = 1;
            for (; index <= count; ++index)
            {
                string path = String.Format("{0}[{1}]/label", RolesLocatorForAddUser, index);
                var text = selenium.GetText(path);
                if (String.CompareOrdinal(Name, text) == 0)
                    break;
            }

            if (index > count)
                throw new CaseFailureException(String.Format("Can't find role {0} in Add User page!", Name));

            return index;
        }

        public int GetRoleIndexOnEditUserPage()
        {
            var count = (int)selenium.GetXpathCount(RolesLocatorForEditUser);
            var index = 1;
            for (; index <= count; ++index)
            {
                string path = String.Format("{0}[{1}]/label", RolesLocatorForEditUser, index);
                var text = selenium.GetText(path);
                if (String.CompareOrdinal(Name, text) == 0)
                    break;
            }

            if (index > count)
                throw new CaseFailureException(String.Format("Can't find role {0} in Edit User page!", Name));

            return index;
        }
    }
}
